<?php
/**
 * 易优CMS
 * ============================================================================
 * 版权所有 2016-2028 海南赞赞网络科技有限公司，并保留所有权利。
 * 网站地址: http://www.eyoucms.com
 * ----------------------------------------------------------------------------
 * 如果商业用途务必到官方购买正版授权, 以免引起不必要的法律纠纷.
 * ============================================================================
 * Author: 小虎哥 <1105415366@qq.com>
 * Date: 2018-06-28
 */

namespace weapp\Seckill\controller;

use think\Page;
use think\Db;
use app\common\controller\Weapp;
use weapp\Seckill\model\SeckillModel;
use app\common\logic\ArctypeLogic;
use weapp\Seckill\logic\SeckillLogic;
use weapp\Seckill\model\SeckillProductSpecValue;
use weapp\Seckill\model\SeckillArchives;

/**
 * 插件的控制器
 */
class Seckill extends Weapp
{
    private $model;
    private $db;
    private $archives_db;
    private $arctypeLogic;
    private $specValuemodel;
    private $seckillArcmodel;
    private $weappInfo;

    /**
     * 构造方法
     */
    public function __construct()
    {
        parent::__construct();
        $this->model = new SeckillModel;
        $this->db = Db::name('WeappSeckill');
        $this->archives_db = Db::name('archives');
        $this->arctypeLogic = new ArctypeLogic();
        $this->seckillLogic = new SeckillLogic;
        $this->specValuemodel = new SeckillProductSpecValue;
        $this->seckillArcmodel = new SeckillArchives;

        /*插件基本信息*/
        $this->weappInfo = $this->getWeappInfo();
        $this->assign('weappInfo', $this->weappInfo);
        /*--end*/
    }

    //安装后置插件
    public function afterInstall()
    {
        $Prefix = config('database.prefix');
        $tableInfo = Db::query("SHOW COLUMNS FROM {$Prefix}shop_order");
        $tableInfo = get_arr_column($tableInfo, 'Field');
        if (!empty($tableInfo) && !in_array('is_seckill_order', $tableInfo)){
            Db::execute("ALTER TABLE `{$Prefix}shop_order` ADD COLUMN `is_seckill_order` int(11) NULL DEFAULT 0 COMMENT '是否为秒杀插件订单 0-否,是的话写入秒杀活动act_id' AFTER `verify_id`");
            schemaTable('shop_order');
        }
    }

    //卸载后置插件
    public function afterUninstall()
    {
        $Prefix = config('database.prefix');
        $tableInfo = Db::query("SHOW COLUMNS FROM {$Prefix}shop_order");
        $tableInfo = get_arr_column($tableInfo, 'Field');
        if (!empty($tableInfo) && in_array('is_seckill_order', $tableInfo)){
            Db::execute("ALTER TABLE `{$Prefix}shop_order` DROP COLUMN `is_seckill_order`");
            schemaTable('shop_order');
        }
    }

    /**
     * 插件后台管理 - 秒杀列表
     */
    public function index()
    {
        $this->db->where('start_time', '>', getTime())->where('status', 'not in', [2, 3])->update(['status' => 2, 'update' => getTime()]);//未开始
        $this->db->where('end_time', '<', getTime())->where('status', 'not in', [3, 4])->update(['status' => 4, 'update' => getTime()]);//已经结束
        $this->db->where('start_time', '<', getTime())->where('end_time', '>', getTime())->where('status', 2)->update(['status' => 1, 'update' => getTime()]);//进行中

        $list = array();
        $keywords = input('keywords/s');
        $title = input('title/s');
        $status = input('status/d');
        $start_time = input('start_time/s');
        $end_time = input('end_time/s');

        $map = array();
        if (!empty($keywords)) {
            $map['a.activity_title'] = array('LIKE', "%{$keywords}%");
        }
        if (!empty($title)) {
            $map['c.title'] = array('LIKE', "%{$title}%");
        }
        if (!empty($status)) {
            $map['a.status'] = $status;
        }
        if (!empty($start_time)) {
            $start_time = strtotime($start_time);
            $map['a.start_time'] = ['>=', $start_time];
        }
        if (!empty($end_time)) {
            $end_time = strtotime($end_time);
            $map['a.end_time'] = ['<=', $end_time];
        }

        if (!empty($title)) {
            $count = $this->db->alias('a')
                ->join('weapp_seckill_archives b', 'a.id = b.act_id', 'left')
                ->join('archives c', 'b.aid = c.aid', 'left')
                ->where($map)->count('a.id');
            $pageObj = new Page($count, config('paginate.list_rows'));
            $list = $this->db->alias('a')->field('a.*,c.title')
                ->join('weapp_seckill_archives b', 'a.id = b.act_id', 'left')
                ->join('archives c', 'b.aid = c.aid', 'left')
                ->where($map)
                ->order('a.status asc,a.id desc')
                ->limit($pageObj->firstRow . ',' . $pageObj->listRows)->select();
        } else {
            $count = $this->db->alias('a')->where($map)->count('a.id');
            $pageObj = new Page($count, config('paginate.list_rows'));
            $list = $this->db->alias('a')->where($map)->order('status asc,id desc')->limit($pageObj->firstRow . ',' . $pageObj->listRows)->select();
        }
        $pageStr = $pageObj->show();
        $this->assign('list', $list);
        $this->assign('pageStr', $pageStr);
        $this->assign('pager', $pageObj);

        $this->seckillArcmodel->where('act_id', 0)->delete();
        $this->specValuemodel->where('act_id', 0)->delete();

        return $this->fetch('index');
    }

    /**
     * 插件后台管理 - 新增
     */
    public function add()
    {
        if (IS_POST) {
            $post = input('post.');
            if (empty($post['activity_title'])) $this->error('活动名称不能为空');
            if (empty($post['start_time'])) $this->error('活动开始时间不能为空');
            if (empty($post['end_time'])) $this->error('活动结束时间不能为空');
            if (empty($post['activity_channel'])) $this->error('活动渠道至少选择一个');
            //判断规格价格是否设置
            foreach ($post['is_spec'] as $k => $v) {
                if (1 == $v) {
                    //多规格
                    if (empty($post['spec_set'][$k])) $this->error('请设置 【' . $post['title'][$k] . '】 秒杀价');
                } else {
                    //单规格
                    if (empty($post['seckill_price'][$k])) $this->error('请设置 【' . $post['title'][$k] . '】 秒杀价');
                }
            }

            $post['start_time'] = strtotime($post['start_time']);
            $post['end_time'] = strtotime($post['end_time']);
            $post['activity_channel'] = ",".implode(',', $post['activity_channel']).",";
            $post['add_time'] = $post['update_time'] = getTime();
            $count = $this->db->count();
            if (0 == $count && $post['start_time'] < getTime() && $post['end_time'] > getTime()){
                $post['in_progress'] = 1;
            }

            $act_id = $this->db->insertGetId($post);
            if (false !== $act_id) {

                $post['id'] = $act_id;
                $this->handle_goods($post, ['act_id' => 0]);

                adminLog('新增活动：' . $post['activity_title']);
                $this->success("操作成功", weapp_url('Seckill/Seckill/index'));
            } else {
                $this->error("操作失败");
            }
        }
        $dealer_open = 0;
        $dealerConfig = getUsersConfigData('dealer');
        if (!empty($dealerConfig['dealer_open'])) $dealer_open = 1;
        $this->assign('dealer_open', $dealer_open);

        return $this->fetch('add');
    }

    //编辑
    public function edit()
    {
        if (IS_POST) {
            $post = input('post.');
            if (empty($post['activity_title'])) $this->error('活动名称不能为空');
            if (empty($post['start_time'])) $this->error('活动开始时间不能为空');
            if (empty($post['end_time'])) $this->error('活动结束时间不能为空');
            if (empty($post['activity_channel'])) $this->error('活动渠道至少选择一个');
            //判断规格价格是否设置
            foreach ($post['is_spec'] as $k => $v) {
                if (1 == $v) {
                    //多规格
                    if (empty($post['spec_set'][$k])) $this->error('请设置 【' . $post['title'][$k] . '】 秒杀价');
                } else {
                    //单规格
                    if (empty($post['seckill_price'][$k])) $this->error('请设置 【' . $post['title'][$k] . '】 秒杀价');
                }
            }

            $post['start_time'] = strtotime($post['start_time']);
            $post['end_time'] = strtotime($post['end_time']);
            $post['activity_channel'] = ",".implode(',', $post['activity_channel']).",";
            $post['update_time'] = getTime();

            $res = $this->db->where('id', $post['id'])->update($post);
            if (false !== $res) {

                $sa_where['act_id'] = $post['id'];
                if (!empty($post['goods_id'])) $sa_where['goods_id'] = ['not in', $post['goods_id']];
                $this->handle_goods($post, $sa_where);

                adminLog('编辑活动：' . $post['activity_title']);
                $this->success("操作成功", weapp_url('Seckill/Seckill/index'));
            } else {
                $this->error("操作失败");
            }
        }
        $dealer_open = 0;
        $dealerConfig = getUsersConfigData('dealer');
        if (!empty($dealerConfig['dealer_open'])) $dealer_open = 1;
        $this->assign('dealer_open', $dealer_open);

        $id = input('id/d', 0);
        $row = $this->db->find($id);
        if (empty($row)) {
            $this->error('数据不存在，请联系管理员！');
        }
        $row['activity_channel'] = explode(',', trim($row['activity_channel'], ','));
        $row['start_time'] = date('Y-m-d H:i:s', $row['start_time']);
        $row['end_time'] = date('Y-m-d H:i:s', $row['end_time']);
        Db::name('weapp_seckill_archives')->where('act_id', $id)->where('temporary_add',1)->delete();
        $aids = Db::name('weapp_seckill_archives')->where('act_id', $id)->column('aid');
        $aids = implode(',', $aids);

        $row['aids'] = $aids;
        $this->assign('info', $row);

        $fetch = input('fetch/s', 'edit');

        $showGoods = $this->showGoods($aids, $id, $fetch);
        $this->assign('showGoods', $showGoods);

        return $this->fetch($fetch);
    }

    //复制
    public function copy_add()
    {
        $this->seckillArcmodel->where('act_id', 0)->delete();
        $this->specValuemodel->where('act_id', 0)->delete();

        $dealer_open = 0;
        $dealerConfig = getUsersConfigData('dealer');
        if (!empty($dealerConfig['dealer_open'])) $dealer_open = 1;
        $this->assign('dealer_open', $dealer_open);

        $id = input('id/d', 0);
        $row = $this->db->find($id);
        if (empty($row)) {
            $this->error('数据不存在，请联系管理员！');
        }
        $row['activity_channel'] = explode(',', trim($row['activity_channel'], ','));
        $row['start_time'] = date('Y-m-d H:i:s', $row['start_time']);
        $row['end_time'] = date('Y-m-d H:i:s', $row['end_time']);

        $this->assign('info', $row);

        // 复制商品
        $goods = $this->seckillArcmodel->where('act_id', $id)->select();
        if (!empty($goods)) {
            $goods_id = get_arr_column($goods, 'goods_id');
            $insert_data = [];
            foreach ($goods as $k => $v) {
                $insert_one = [
                    'aid' => $v['aid'],
                    'seckill_price' => $v['seckill_price'],
                    'seckill_stock' => $v['seckill_stock'],
                    'price' => $v['price'],
                    'stock' => $v['stock'],
                    'is_spec' => $v['is_spec'],
                    'temporary_add' => 1,
                    'add_time' => getTime(),
                    'update_time' => getTime(),
                ];
                $insert_data[] = $insert_one;
            }
            if (!empty($insert_data)) {
                $this->seckillArcmodel->saveAll($insert_data);

                $new_goods = $this->seckillArcmodel->where('act_id', 0)->field('aid,goods_id')->getAllWithIndex('aid');
                $aids = get_arr_column($new_goods, 'aid');
                $goodsSpec = $this->specValuemodel->where('act_id', $id)->select();

                if (!empty($goodsSpec)) {
                    $spec_insert_data = [];
                    foreach ($goodsSpec as $k => $v) {
                        $spec_insert_one = [
                            'goods_id' => $new_goods[$v['aid']]['goods_id'],
                            'aid' => $v['aid'],
                            'spec_value_id' => $v['spec_value_id'],
                            'seckill_price' => $v['seckill_price'],
                            'seckill_stock' => $v['seckill_stock'],
                            'is_join' => 1,
                            'add_time' => getTime(),
                            'update_time' => getTime(),
                        ];
                        $spec_insert_data[] = $spec_insert_one;
                    }
                    if (!empty($spec_insert_data)) $this->specValuemodel->saveAll($spec_insert_data);
                }
            }
        }

        $showGoods = $this->showGoods($aids);
        $this->assign('showGoods', $showGoods);

        return $this->fetch();
    }

    //保存/编辑/删除秒杀商品
    private function handle_goods($post = [], $where = '')
    {
        if (!empty($post['goods_id'])) {
            $update = [];
            foreach ($post['is_spec'] as $k => $v) {
                $update_data = [
                    'goods_id' => $post['goods_id'][$k],
                    'is_spec' => $v,
                    'act_id' => $post['id'],
                    'temporary_add' => 0,
                    'update_time' => getTime()
                ];
                if (empty($v)) {
                    $update_data['seckill_price'] = $post['seckill_price'][$k];
                    $update_data['seckill_stock'] = $post['seckill_stock'][$k];
                }
                $update[] = $update_data;
            }
            $this->seckillArcmodel->saveAll($update);
            $this->specValuemodel->where('goods_id', 'in', $post['goods_id'])->update(['act_id' => $post['id'], 'update_time' => getTime()]);
        }
        //需要删除的商品
        $del_goods_ids = $this->seckillArcmodel->where($where)->column('goods_id');
        if (!empty($del_goods_ids)) {
            $this->seckillArcmodel->where('goods_id', 'in', $del_goods_ids)->delete();
            $this->specValuemodel->where('goods_id', 'in', $del_goods_ids)->delete();
        }
        return true;
    }

    /**
     * 插件配置
     */
    public function conf()
    {
        if (IS_POST) {
            // 接收配置信息
            $post_seckill = input('post.seckill/a', []);
            // 判断配置信息
            if (!empty($post_seckill['seckill_close_order_type']) && empty($post_seckill['seckill_close_order_time'])) $this->error('请填写订单关闭时间');
            if (empty($post_seckill['seckill_close_order_type']) && !empty($post_seckill['seckill_close_order_time'])) unset($post_seckill['seckill_close_order_time']);
            if (!empty($post_seckill['seckill_close_order_time']) && (5 > $post_seckill['seckill_close_order_time'] || $post_seckill['seckill_close_order_time'] > 60)) $this->error('订单关闭时间必须在5-60分钟之间');
            // 保存配置信息
            getUsersConfigData('seckill', $post_seckill);
            adminLog('编辑' . $this->weappInfo['name'] . '：插件配置'); // 写入操作日志
            $this->success("操作成功!", weapp_url('Seckill/Seckill/conf'));
        }

        $seckill = getUsersConfigData('seckill');
        $this->assign('config', $seckill);

        return $this->fetch('conf');
    }

    //手动停止活动
    public function stop_activity()
    {
        if (IS_POST) {
            $id = input('param.id/d');
            $update_data['status'] = 3;
            $update_data['stop_time'] = getTime();
            $res = $this->db->where('id', $id)->update($update_data);
            if (false !== $res) {
                adminLog("停止活动(id:{$id})"); // 写入操作日志
                $this->success("停止成功!", weapp_url('Seckill/Seckill/index'));
            } else {
                $this->error("停止失败!");
            }
        }
        $this->error("请求失败!");
    }

    /**
     * 选择秒杀商品
     */
    public function ajax_archives_list()
    {
        $aid = input('aid/s');
        // 查询条件
        $where['a.channel'] = 2;
        $where['a.arcrank'] = 0; //开放浏览商品
        $where['a.status'] = 1;
        $where['a.is_del'] = 0;
        if (!empty($aid)) $where['a.aid'] = ['not in', $aid];

        $keywords = input('keywords/s');
        if (!empty($keywords)) $where['a.title'] = ['LIKE', "%{$keywords}%"];

        // 指定商品ID查询
        $product_ids = input('product_ids/s');
        if (!empty($product_ids)) $where['a.aid'] = ['IN', explode(',', $product_ids)];

        $stypeidwhere = '';
        // 指定分类查询
        $param = input('param.');
        $stypeid = $param['stypeid'];
        if (!empty($stypeid)) {
            $this->assign('stypeidStr', implode(',', $stypeid));
            $this->assign('stypeidCount', '已选中 ' . count($stypeid) . ' 个分类');
            $stypeid_arr = [];
            foreach ($stypeid as $val) {
                $stypeid_arr[] = '(a.stypeid LIKE \'%,' . $val . ',%\')';
            }
            $stypeidwhere = !empty($stypeid_arr) ? implode(' OR ', $stypeid_arr) : '';
        }

        $count = $this->archives_db->alias('a')->where($where)->count();
        $pageObj = new Page($count, config('paginate.list_rows'));
        $this->assign('page', $pageObj->show());
        $this->assign('pager', $pageObj);

        $field = 'a.aid, a.litpic, a.title, a.users_price,a.stock_count';
        $ResultData = $this->archives_db
            ->alias('a')
            ->field($field)
            ->where($where)
            ->where($stypeidwhere)
            ->order('a.sort_order asc, a.users_price desc, a.aid desc')
            ->limit($pageObj->firstRow . ',' . $pageObj->listRows)
            ->select();

        $aids = get_arr_column($ResultData, 'aid');
        $spec_value = Db::name('product_spec_value')
            ->field('min(spec_price) as min_spec_price,max(spec_price) as max_spec_price,sum(spec_stock) as spec_stock,aid')
            ->group('aid')
            ->where('aid', 'in', $aids)
            ->getAllWithIndex('aid');
        foreach ($ResultData as $k => $v) {
            if (!empty($spec_value[$v['aid']])) {
                $v['min_price'] = $spec_value[$v['aid']]['min_spec_price'];
                if ($spec_value[$v['aid']]['min_spec_price'] != $spec_value[$v['aid']]['max_spec_price']) {
                    $v['max_price'] = $spec_value[$v['aid']]['max_spec_price'];
                }
                $v['stock_count'] = $spec_value[$v['aid']]['spec_stock'];
            } else {
                $v['min_price'] = $v['users_price'];
            }
            $v['litpic'] = handle_subdir_pic($v['litpic']);
            unset($ResultData[$k]['users_price']);
            $ResultData[$k] = $v;
        }
        $this->assign('list', $ResultData);

        // 分类列表
        $where = [
            'is_del' => 0,
            'current_channel' => 2
        ];
        $arctype_list = $this->arctypeLogic->arctype_list(0, 0, false, 0, $where, false);
        foreach ($arctype_list as $key => $value) {
            $value['litpic'] = get_default_pic($value['litpic']);
            $arctype_list[$key] = $value;
        }
        $this->assign('arctype_list', $arctype_list);
        // 获取所有有子栏目的栏目id
        $where = [
            'is_del' => 0,
            'parent_id' => ['gt', 0]
        ];
        $parent_ids = Db::name('arctype')->where($where)->group('parent_id')->cache(true, EYOUCMS_CACHE_TIME, 'arctype')->column('parent_id');
        $cookied_treeclicked = json_decode(cookie('stypeid-treeClicked-Arr'));
        empty($cookied_treeclicked) && $cookied_treeclicked = [];
        $all_treeclicked = cookie('stypeid-treeClicked_All');
        empty($all_treeclicked) && $all_treeclicked = [];
        $tree = [
            'has_children' => !empty($parent_ids) ? 1 : 0,
            'parent_ids' => json_encode($parent_ids),
            'all_treeclicked' => $all_treeclicked,
            'cookied_treeclicked' => $cookied_treeclicked,
            'cookied_treeclicked_arr' => json_encode($cookied_treeclicked),
        ];
        $this->assign('tree', $tree);

        return $this->fetch();
    }

    /**
     * 活动数据
     */
    public function active_sale_data()
    {
        $id = input('id/d', 0);

        $map['a.act_id'] = $id;
        $count = $this->seckillArcmodel->alias('a')->where($map)->count('a.goods_id');
        $pageObj = new Page($count, config('paginate.list_rows'));
        $list = Db::name('weapp_seckill_archives')->alias('a')
            ->field('a.*,b.litpic,b.title')
            ->join('archives b', 'a.aid = b.aid', 'left')
            ->where($map)
            ->order('a.goods_id desc')
            ->limit($pageObj->firstRow . ',' . $pageObj->listRows)
            ->select();
        $aid = get_arr_column($list,'aid');

        $where['a.is_seckill_order'] = $id;
        $where['b.product_id'] = ['in',$aid];
        $where['a.order_status'] = 3;//已完成订单
        $order_count = Db::name('shop_order')
            ->alias('a')
            ->join('shop_order_details b','a.order_id = b.order_id')
            ->field('b.product_id as aid,sum(b.num) as num')
            ->where($where)
            ->group('b.product_id')
            ->getAllWithIndex('aid');
        foreach ($list as $k => $v) {
            $v['litpic'] = handle_subdir_pic($v['litpic']);
            $v['order_success_count'] = !empty($order_count[$v['aid']]) ? $order_count[$v['aid']]['num'] : 0;
            $list[$k] = $v;
        }
        $pageStr = $pageObj->show();
        $this->assign('list', $list);
        $this->assign('pageStr', $pageStr);
        $this->assign('pager', $pageObj);

        return $this->fetch('active_sale_data');
    }


    /**
     * 查看参与的活动
     */
    public function get_join_activity()
    {
        $aid = input('aid/d', 0);

        $where['aid'] = $aid;
        $count = $this->seckillArcmodel->alias('a')->where($where)->count('a.act_id');
        $pageObj = new Page($count, config('paginate.list_rows'));
        $list = $this->seckillArcmodel->alias('a')
            ->field('a.act_id,b.*')
            ->join('weapp_seckill b', 'a.act_id = b.id', 'left')
            ->where($where)
            ->order('act_id desc')
            ->limit($pageObj->firstRow . ',' . $pageObj->listRows)
            ->select();
        $pageStr = $pageObj->show(); // 分页显示输出
        $this->assign('list', $list); // 赋值数据集
        $this->assign('pageStr', $pageStr); // 赋值分页输出
        $this->assign('pager', $pageObj); // 赋值分页对象

        return $this->fetch('get_join_activity');
    }

    /**
     * 修改多规格商品
     */
    public function multi_specification_list()
    {
        if (IS_AJAX_POST) {
            $post = input('post.');
            // 设置商品规格信息
            $this->specValuemodel->setGoodsSpec($post);
        }

        $aid = input('param.aid/d', 0);
        $goods_id = input('param.goods_id/d', 0);
        if (empty($aid) || empty($goods_id)) $this->error('请选择商品');
        $this->assign('aid', $aid);
        $this->assign('goods_id', $goods_id);

        // 查询商品已选的规格值ID数组
        $where = [
            'aid' => $aid,
            'spec_is_select' => 1,
        ];
        $field = 'spec_mark_id, spec_value_id';
        $order = 'spec_value_id asc, spec_id asc';
        $goodsSpec = Db::name('product_spec_data')->field($field)->where($where)->order($order)->select();
        $goodsSpec = !empty($goodsSpec) ? group_same_key($goodsSpec, 'spec_mark_id') : [];
        foreach ($goodsSpec as $key => $value) {
            for ($i = 0; $i < count($value); $i++) {
                $goodsSpec[$key][$i] = $value[$i]['spec_value_id'];
            }
        }
        $fetch = input('get.fetch/s');
        $this->assign('fetch', $fetch);
        // 获取商品规格组合Html
        $goodsSpecCombi = $this->seckillLogic->getGoodsSpecCombi($goodsSpec, $aid, $goods_id,$fetch);
        $this->assign('goodsSpecCombi', $goodsSpecCombi);


        return $this->fetch('multi_specification_list');
    }

    /**
     * 删除文档
     */
    public function del()
    {
        $id_arr = input('del_id/a');
        $id_arr = eyIntval($id_arr);
        if (!empty($id_arr) && IS_POST) {
            $result = $this->db->where("id", 'IN', $id_arr)->select();
            $title_list = get_arr_column($result, 'title');
            $r = $this->db->where("id", 'IN', $id_arr)->delete();
            if ($r) {
                adminLog('删除' . $this->weappInfo['name'] . '：' . implode(',', $title_list));
                $this->seckillArcmodel->where('act_id', 'in', $id_arr)->delete();
                $this->specValuemodel->where('act_id', 'in', $id_arr)->delete();
                $this->success("操作成功!");
            } else {
                $this->error("操作失败!");
            }
        } else {
            $this->error("参数有误!");
        }
    }

    //开启/关闭 活动
    public function set_in_progress()
    {
        if (IS_AJAX_POST) {
            $id = input('param.id/d'); // 表主键id值
            $value = input('param.value/d'); // 修改字段值

            /*处理数据的安全性*/
            if (empty($id)) {
                $this->error('活动不存在！');
            }
            if (!empty($value)) {
                Db::name('weapp_seckill')->where('in_progress', 1)->update(['in_progress' => 0, 'update_time' => getTime()]);
            }

            // 根据条件保存修改的数据
            $r = Db::name('weapp_seckill')->where('id', $id)->update(['in_progress' => $value, 'update_time' => getTime()]);
            if ($r !== false) {
                $this->success('设置成功');
            }
        }
        $this->error('设置失败');
    }

    // 加载显示商品
    public function showGoods($aidStr = '', $act_id = 0, $fetch = '')
    {
        if (IS_AJAX_POST || !empty($aidStr)) {
            $aidStr = !empty($aidStr) ? $aidStr : input('post.aidStr/s', '');
            $act_id = !empty($act_id) ? $act_id : input('post.act_id/d');

            // 查询商品信息
            $where = [
                'aid' => ['IN', $aidStr]
            ];
            $field = 'aid, title, litpic, users_price, stock_count';
            $goodsList = Db::name('archives')
                ->field($field)
                ->where($where)
                ->order('aid desc')
                ->select();
            $aids = get_arr_column($goodsList, 'aid');

            $spec_value = Db::name('product_spec_value')
                ->field('min(spec_price) as min_spec_price,max(spec_price) as max_spec_price,sum(spec_stock) as spec_stock,aid')
                ->group('aid')
                ->where('aid', 'in', $aids)
                ->getAllWithIndex('aid');
            $insert = [];
            $sec_arc_where = [
                'aid' => ['IN', $aidStr]
            ];
            $sec_arc_where['act_id'] = $act_id;
//            $sec_arc_where['temporary_add'] = 1;
            $is_have_aid = Db::name('weapp_seckill_archives')->where($sec_arc_where)->column('aid');

            foreach ($goodsList as $k => $v) {
                $v['seckill_price'] = '￥';
                if (!empty($spec_value[$v['aid']])) {
                    $v['seckill_price'] .= $spec_value[$v['aid']]['min_spec_price'];
                    if ($spec_value[$v['aid']]['min_spec_price'] != $spec_value[$v['aid']]['max_spec_price']) {
                        $v['seckill_price'] .= " ~ ￥{$spec_value[$v['aid']]['max_spec_price']}";
                    }
                    $v['stock_count'] = $spec_value[$v['aid']]['spec_stock'];
                } else {
                    $v['seckill_price'] .= $v['users_price'];
                }
                $v['litpic'] = handle_subdir_pic($v['litpic']);
                $v['is_spec'] = !empty($spec_value[$v['aid']]) ? 1 : 0;
                if (!in_array($v['aid'], $is_have_aid)) {
                    $insert[] = [
                        'aid' => $v['aid'],
                        'act_id' => !empty($act_id) ? $act_id : 0,
                        'temporary_add' => 1,
                        'is_spec' => $v['is_spec'],
                        'price' => $v['users_price'],
                        'stock' => $v['stock_count'],
                    ];
                }

                unset($goodsList[$k]['users_price']);
                $goodsList[$k] = $v;
            }
            if (!empty($insert)) Db::name('weapp_seckill_archives')->insertAll($insert);

            $goods_data = Db::name('weapp_seckill_archives')->where('act_id', $act_id)->getAllWithIndex('aid');
            $spec_set = Db::name('weapp_seckill_product_spec_value')->where('act_id', $act_id)->field('goods_id,aid,count(value_id) as count')->group('aid')->getAllWithIndex('aid');

            foreach ($goodsList as $k => $v) {
                $goodsList[$k]['goods_id'] = $goods_data[$v['aid']]['goods_id'];
                $goodsList[$k]['spec_set'] = !empty($spec_set[$v['aid']]['count']) ? 1 : 0;
                $goodsList[$k]['price'] = $goods_data[$v['aid']]['price'];
                $goodsList[$k]['stock'] = $goods_data[$v['aid']]['stock'];
                $goodsList[$k]['seckill_price'] = $goods_data[$v['aid']]['seckill_price'];
                $goodsList[$k]['seckill_stock'] = $goods_data[$v['aid']]['seckill_stock'];
            }
            $this->assign('goodsList', $goodsList);
            $this->assign('fetch', $fetch);
            return $this->fetch('show_goods');
        }
    }
}